package com.ltv.xiangqibook.web;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;

public class TreeGenerator {
	private static final Logger logger = Logger.getLogger(TreeGenerator.class.getCanonicalName());
    private static TreeGenerator instance;
    private StringBuffer tree;
    
    private TreeGenerator() {
    }
    
    public static TreeGenerator getInstance() {
        if (instance == null) {
            instance = new TreeGenerator();
        }
        
        return instance;
    }
    
    public synchronized void initTree(String gameUrlBase) {
        tree = new StringBuffer();
        tree.append("<ul id=\"browser\" class=\"filetree\">\n");
        
        BufferedReader fileReader = null;
        try {
            fileReader = new BufferedReader(
                    new InputStreamReader(
                    		new FileInputStream(
                    				"xml/" + XiangQiBookConfiguration.getInstance().getXmlVersion() + "/xiangqibook-tree.xml")
                    		, "utf-8"));
            String line = fileReader.readLine();
            line = fileReader.readLine();
            line = fileReader.readLine();
            
            List<String> lines = new ArrayList<String>();
            
            while (line != null) {
                lines.add(line);
                line = fileReader.readLine();
            }
            
            lines.remove(lines.get(lines.size() - 1));
            
            for (String l : lines) {
                tree.append(toHtmlLine(l, gameUrlBase) + "\n");
            }
            tree.append("</ul>\n");
        } catch (Exception e) {
        	logger.severe("Error initializing tree: " + e.getMessage());
        } finally {
            if (fileReader != null) {
                try {
					fileReader.close();
				} catch (IOException e) {
					logger.severe("Error closing file reader: " + e.getMessage());
				}
            }
        }
    }
    
    private boolean isCssOpened(String fullPath, String gameBaseUrl) {
        if (gameBaseUrl == null || gameBaseUrl == null) {
            return false;
        }
        
        String array1[] = fullPath.split("/");
        String array2[] = gameBaseUrl.split("/");
        
        if (array1.length > array2.length) {
            return false;
        }
        
        for (int i = 0; i < array1.length; i++) {
            if (!array1[i].equals(array2[i])) {
                return false;
            }
        }
        
        return true;
    }
    
    private String toHtmlLine(String xmlLine, String gameUrlBase) throws Exception {
        String ret = "";
        if (xmlLine.trim().startsWith("<Folder") && xmlLine.trim().endsWith("\"/>")) {
            String fullPath = getFullPath(xmlLine);
            if (fullPath != null) {
                xmlLine = xmlLine.replace(" fullpath=\"" + fullPath + "\"", "");
            }
            ret = "";
            ret = xmlLine.replace("\"/>", "</span></li>");
            
            String liCssClass = "closed";
            if (isCssOpened(fullPath, gameUrlBase)) {
                liCssClass = "opened";
            }
            ret = ret.replace("<Folder value=\"", "<li class=\"" + liCssClass + "\"><span class=\"folder\">");
            
            return ret;
        }
        
        if (xmlLine.trim().startsWith("<Folder") && xmlLine.trim().endsWith("\">")) {
            String fullPath = getFullPath(xmlLine);
            if (fullPath != null) {
                xmlLine = xmlLine.replace(" fullpath=\"" + fullPath + "\"", "");
            }
            ret = "";
            ret = xmlLine.replace("\">", "</span><ul>");
            
            String liCssClass = "closed";
            if (isCssOpened(fullPath, gameUrlBase)) {
                liCssClass = "opened";
            }
            
            ret = ret.replace("<Folder value=\"", "<li class=\"" + liCssClass + "\"><span class=\"folder\">");
            
            return ret;
        }
        
        if (xmlLine.trim().equals("</Folder>")) {
            ret = "";
            ret = xmlLine.replace("</Folder>", "</ul></li>");
            
            return ret;
        }
        
        if (xmlLine.trim().startsWith("<File") && xmlLine.trim().endsWith("\"/>")) {
            ret = "";
            ret = xmlLine.replace("\"/>", "</a></span></li>");
            ret = ret.replace("<File game_id=\"", "<li><span class=\"file\"><a href=\"../XiangQiGame?game_id=");
            ret = ret.replace("value=\"", "target=\"game\">");
            
            return ret;
        }
        return ret;
    }

    public String getTree() {
        if (tree != null) {
            return tree.toString();
        }
        
        return "";
    }
    
    public static void main(String[] args) {
        System.out.println(TreeGenerator.getInstance().getTree());
    }
    
    
    private String getFullPath(String xmlLine) {
        StringTokenizer st = new StringTokenizer(xmlLine, "=\"");
        while(st.hasMoreTokens()) {
            String key = st.nextToken();
            String val = "";
            if (st.hasMoreTokens()) {
                val = st.nextToken();
            }
            if (key.indexOf("fullpath") != -1) {
                return val;
            }
        }
        
        return null;
    }
    
}
